<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // Vector 构造函数
        function Vector (x = 0, y = 0) {
            this.x = x;
            this.y = y;
        }

        // 对象池构造函数
        function VectorPool () {
            this.pool = [] // 存储可以重用的Vector对象
        }

        // 从对象池中分配一个Vector对象
        VectorPool.prototype.allocate = function () {
            // 如果对象池有对象，直接取出返回
            if (this.pool.length > 0) {
                return this.pool.pop()
            }
            // 如果没有，则创建一个
            return new Vector()
        }
        // 从对象池中分配一个Vector对象
        VectorPool.prototype.free = function (vector) {
            this.pool.push(vector)
        }
        function addVector (a, b) {
            let resultant = new Vector();
            resultant.x = a.x + b.x;
            resultant.y = a.y + b.y;
            return resultant;
        }
        // 改造
        function addVector2 (a, b, resultant) {
            resultant.x = a.x + b.x;
            resultant.y = a.y + b.y;
            return resultant;
        }
        const vectorPool = new VectorPool()
        // vectorPool是已有的对象池
        let v1 = vectorPool.allocate();
        let v2 = vectorPool.allocate();
        let v3 = vectorPool.allocate();

        v1.x = 10;
        v1.y = 5;
        v2.x = -3;
        v2.y = -6;

        addVector2(v1, v2, v3)

        console.log([v3.x, v3.y], '[v3.x, v3.y]');

        vectorPool.free(v1);
        vectorPool.free(v2);
        vectorPool.free(v3);

        v1 = null;
        v2 = null;
        v3 = null;
    </script>
</body>
</html>